// 修改导入方式
import { CardPattern, CardUtils } from './utils/cardUtils.js';

let stompClient = null;
let currentPlayer = null;
let currentRoom = null;
let currentGameState = null;

function initGame() {
    // 从 URL 获取房间 ID
    const urlParams = new URLSearchParams(window.location.search);
    const roomId = urlParams.get('roomId');

    // 从 localStorage 获取玩家信息
    const playerData = localStorage.getItem('player');
    if (!playerData) {
        window.location.href = '/';
        return;
    }
    currentPlayer = JSON.parse(playerData);

    // 加载房间信息
    loadRoomInfo(roomId);

    // 连接 WebSocket
    connect(roomId);

    // 绑定按钮事件
    bindEvents();

    // 初始化移动端菜单
    initMobileMenu();
}

function loadRoomInfo(roomId) {
    $.get(`/api/game/rooms/${roomId}`)
        .done(function(room) {
            currentRoom = room;
            updateRoomUI(room);
        })
        .fail(function(error) {
            console.error('加载房间信息失败:', error);
            showGameMessage('加载房间信息失败', 'error');
        });
}

function connect(roomId) {
    console.log('Connecting to WebSocket...');
    const socket = new SockJS('/ws');
    stompClient = Stomp.over(socket);

    stompClient.debug = null; // 禁用调试日志

    const headers = {
        playerId: currentPlayer.id,
        roomId: roomId
    };

    showGameMessage('正在连接游戏服务器...', 'info');

    stompClient.connect(headers,
        function(frame) {
            console.log('Connected: ' + frame);
            showGameMessage('连接成功！', 'success');
            reconnectAttempts = 0; // 重置重连次数

            // 订阅房间更新消息
            stompClient.subscribe(`/topic/room/${roomId}`, function(message) {
                console.log('Received room update:', message);
                const room = JSON.parse(message.body);
                updateRoomUI(room);
            });

            // 订阅游戏状态更新消息
            stompClient.subscribe(`/topic/game/${roomId}`, function(message) {
                console.log('Received game update:', message);
                const gameState = JSON.parse(message.body);

                // 如果是新游戏开始且房间状态为等待中
                if (gameState.status === 'WAITING' && gameState.room.status === 'WAITING') {
                    showGameMessage('新一局游戏即将开始！', 'success');
                }

                updateGameUI(gameState);
            });

            // 订阅游戏状态更新消息
            stompClient.subscribe(`/topic/game/${roomId}/player/${currentPlayer.id}`, function(message) {
                console.log('Received game status update:', message);
                const gameMessage = JSON.parse(message.body);

                if (gameMessage.type === 'ROOM_CLOSED') {
                    showGameMessage('新一局游戏即将开始！', gameMessage.content);
                }

            });

            // 订阅个人消息
            stompClient.subscribe(`/user/queue/private`, function(message) {
                console.log('Received private message:', message);
                handlePrivateMessage(JSON.parse(message.body));
            });

            // 发送玩家加入消息
            stompClient.send(`/app/room/${roomId}/join`, {},
                JSON.stringify(currentPlayer));
        },
        function(error) {
            console.error('STOMP error:', error);
            handleConnectionError();
        }
    );

    socket.onclose = function() {
        console.log('WebSocket connection closed');
        handleConnectionError();
    };
}

function updateRoomUI(room) {
    // 更新房间名称和状态
    $('#roomName').text(room.roomName);
    $('#gameStatus').text(getStatusText(room.status));

    // 更新玩家列表
    const playersList = $('#playersList');
    playersList.empty();

    room.players.forEach(player => {
        const isCurrentPlayer = player.id === currentPlayer.id;
        const playerItem = `
            <li>
                ${player.username} 
                ${isCurrentPlayer ? '(我)' : ''}
                <span class="player-status">
                    ${player.ready ? '<span class="player-ready">已准备</span>' : '<span class="player-waiting">未准备</span>'}
                </span>
            </li>
        `;
        playersList.append(playerItem);
    });

    // 更新其他玩家显示和他们的卡牌数量
    updateOtherPlayers(room.players);

    // 更新准备按钮状态
    updateReadyButton(room);

    // 更新移动端玩家列表
    updateMobilePlayersList(room.players);
}

function updateOtherPlayers(players) {
    const otherPlayers = players.filter(p => p.id !== currentPlayer.id);

    // 更新左边玩家
    if (otherPlayers[0]) {
        $('#player1').html(`
            <div class="player-info">
                <div class="player-name">${otherPlayers[0].username}</div>
                <div class="player-status">${otherPlayers[0].ready ? '已准备' : '未准备'}</div>
                ${otherPlayers[0].cards ? `
                    <div class="card-count">
                        剩余牌数: ${otherPlayers[0].cards.length}
                    </div>
                    <div class="cards-back">
                        ${generateCardBacks(otherPlayers[0].cards.length)}
                    </div>
                ` : ''}
            </div>
        `);
    } else {
        $('#player1').html('等待玩家加入...');
    }

    // 更新右边玩家
    if (otherPlayers[1]) {
        $('#player2').html(`
            <div class="player-info">
                <div class="player-name">${otherPlayers[1].username}</div>
                <div class="player-status">${otherPlayers[1].ready ? '已准备' : '未准备'}</div>
                ${otherPlayers[1].cards ? `
                    <div class="card-count">
                        剩余牌数: ${otherPlayers[1].cards.length}
                    </div>
                    <div class="cards-back">
                        ${generateCardBacks(otherPlayers[1].cards.length)}
                    </div>
                ` : ''}
            </div>
        `);
    } else {
        $('#player2').html('等待玩家加入...');
    }
}

function generateCardBacks(count) {
    let backs = '';
    const maxDisplay = Math.min(count, 10); // 最多显示10张牌背
    for (let i = 0; i < maxDisplay; i++) {
        backs += `<div class="card-back" style="left: ${i * 15}px"></div>`;
    }
    return backs;
}

function displayCards(cards, animate = false) {
    const myCards = $('#myCards');
    myCards.empty();

    if (!cards || cards.length === 0) {
        console.log('No cards to display');
        return;
    }

    // 对卡牌进行排序（按照权重和花色）
    cards.sort((a, b) => {
        if (a.weight !== b.weight) {
            return b.weight - a.weight; // 权重大的在前
        }
        return a.suit.localeCompare(b.suit); // 同权重按花色排
    });

    // 计算每张牌的位置
    const cardWidth = 80; // 卡牌宽度
    const gap = 30; // 卡牌间距
    const totalWidth = (cards.length - 1) * gap + cardWidth;
    const startX = (myCards.width() - totalWidth) / 2;

    cards.forEach((card, index) => {
        const cardElement = $(`
            <div class="card-item ${card.selected ? 'selected' : ''}" 
                 data-card-id="${card.id}"
                 data-suit="${card.suit}" 
                 data-rank="${card.rank}"
                 style="left: ${startX + index * gap}px">
                <div class="card-inner">
                    <span class="card-suit ${isRedSuit(card.suit, card.rank) ? 'red' : ''}">${getSuitSymbol(card.suit)}</span>
                    <span class="card-rank ${isRedSuit(card.suit, card.rank) ? 'red' : ''}">${card.rank}</span>
                </div>
            </div>
        `);

        if (animate) {
            cardElement.css({
                'opacity': '0',
                'transform': 'translateY(20px)'
            });

            setTimeout(() => {
                cardElement.css({
                    'transition': 'all 0.3s ease',
                    'opacity': '1',
                    'transform': 'translateY(0)'
                });
            }, index * 50);
        }

        myCards.append(cardElement);
    });

    // 绑定卡牌点击事件
    bindCardClickEvents();
}

function isRedSuit(suit, rank) {
    return suit === 'HEARTS' || suit === 'DIAMONDS' || rank === 'BIG' || rank === '大王';
}

function bindCardClickEvents() {
    $('.card-item').click(function() {
        const card = $(this);

        // 添加点击动画
        card.addClass('card-clicked');
        setTimeout(() => card.removeClass('card-clicked'), 200);

        // 切换选中状态
        card.toggleClass('selected');

        // 播放音效
        playCardSound(card.hasClass('selected') ? 'select' : 'deselect');

        // 获取所有选中的牌
        const selectedCards = [];
        $('.card-item.selected').each(function() {
            selectedCards.push({
                id: $(this).data('card-id'),
                suit: $(this).data('suit'),
                rank: $(this).data('rank'),
                weight: CardUtils.getCardWeight($(this).data('rank'))
            });
        });

        // 显示牌型提示
        if (selectedCards.length > 0) {
            showPlayingTips(selectedCards);
        }

        updatePlayButtonState();
    });
}

function updatePlayButtonState() {
    const selectedCards = $('.card-item.selected').length;
    const isMyTurn = currentGameState && currentGameState.currentPlayerId === currentPlayer.id;

    $('#playCards').prop('disabled', selectedCards === 0 || !isMyTurn);

    // 如果不是自己的回合，显示提示
    if (!isMyTurn && selectedCards > 0) {
        showGameMessage('还没轮到你出牌', 'warning');
    }
}

function bindEvents() {
    // 准备按钮事件
    $('#readyBtn').click(function() {
        if (!currentRoom) return;

        const btn = $(this);
        btn.addClass('btn-clicked');

        // 添加加载状态
        const originalText = btn.html();
        btn.html('<i class="fas fa-spinner fa-spin"></i> 准备中...');
        btn.prop('disabled', true);

        stompClient.send(`/app/room/${currentRoom.id}/ready`, {},
            JSON.stringify(currentPlayer));

        // 1秒后恢复按钮状态
        setTimeout(() => {
            btn.removeClass('btn-clicked');
            btn.html(originalText);
            btn.prop('disabled', false);
        }, 1000);
    });

    // 离开房间事件
    $('#leaveRoom').click(function() {
        leaveRoom();
    });
}

function showBiddingUI(gameState) {
    const isMyTurn = gameState.currentBidder === currentPlayer.id;
    const currentMaxBid = gameState.maxBid || 0;

    // 创建叫分按钮组
    const biddingControls = `
        <div class="bidding-controls">
            <div class="current-bid-info">
                当前最高分: <span class="max-bid">${currentMaxBid}</span>
            </div>
            <div class="bid-buttons">
                ${generateBidButtons(currentMaxBid)}
            </div>
        </div>
    `;

    $('.game-controls').html(biddingControls);

    // 设置按钮状态
    $('.bid-btn').prop('disabled', !isMyTurn);

    // 显示当前状态
    if (isMyTurn) {
        showGameMessage('轮到你叫分了');
    } else {
        const currentBidder = currentRoom.players.find(p => p.id === gameState.currentBidder);
        showGameMessage(`等待 ${currentBidder ? currentBidder.username : '其他玩家'} 叫分`);
    }

    // 绑定叫分事件
    $('.bid-btn').click(function() {
        if (!isMyTurn) return;

        const bidPoints = $(this).data('bid');
        sendBid(bidPoints);

        // 禁用所有按钮，防止重复点击
        $('.bid-btn').prop('disabled', true);
    });
}

function showPlayingUI(gameState) {
    const isMyTurn = gameState.currentPlayerId === currentPlayer.id;
    const canPass = gameState.lastPlayerId && gameState.lastPlayerId !== currentPlayer.id;

    const playingControls = `
        <div class="playing-controls">
            <button id="playCards" class="btn btn-success" ${!isMyTurn ? 'disabled' : ''}>
                <i class="fas fa-play"></i> 出牌
            </button>
            <button id="pass" class="btn btn-secondary" ${(!isMyTurn || !canPass) ? 'disabled' : ''}>
                <i class="fas fa-times"></i> 不出
            </button>
        </div>
    `;

    $('.game-controls').html(playingControls);
    bindPlayingEvents();
}

function bindPlayingEvents() {
    // 出牌按钮事件
    $('#playCards').click(function() {
        if (!currentRoom) return;

        // 检查是否轮到当前玩家出牌
        const gameState = currentGameState;
        if (gameState && gameState.currentPlayerId !== currentPlayer.id) {
            showGameMessage('还没轮到你出牌', 'warning');
            return;
        }

        const selectedCards = $('.card-item.selected');
        if (selectedCards.length === 0) {
            showGameMessage('请选择要出的牌', 'warning');
            return;
        }

        // 收选中的牌
        const cards = [];
        selectedCards.each(function() {
            cards.push({
                id: $(this).data('card-id'),
                suit: $(this).data('suit'),
                rank: $(this).data('rank'),
                weight: CardUtils.getCardWeight($(this).data('rank'))
            });
        });

        // 验证出牌是否合法
        const pattern = CardUtils.getPattern(cards);
        if (pattern === CardPattern.INVALID) {
            showGameMessage('出牌不合法', 'error');
            return;
        }

        // 如果有上家出牌，需验证是否能大过上家的牌
        if (gameState.lastPlayedCards && gameState.lastPlayedCards.length > 0) {
            if (!CardUtils.canBeatLastCards(cards, gameState.lastPlayedCards)) {
                showGameMessage('出的牌必须大于上家的牌', 'error');
                return;
            }
        }

        // 发送出牌消息
        const cardIds = cards.map(card => card.id);
        sendPlayCards(cardIds);

        // 禁用按钮防止重复点击
        $(this).prop('disabled', true);
    });

    // 不出按钮事件
    $('#pass').click(function() {
        if (!currentRoom) return;

        // 检查是否轮到当前玩家出牌
        const gameState = currentGameState;
        if (gameState && gameState.currentPlayerId !== currentPlayer.id) {
            showGameMessage('还没轮到你出牌', 'warning');
            return;
        }

        // 发送不出消息
        stompClient.send(`/app/game/${currentRoom.id}/pass`, {},
            JSON.stringify(currentPlayer));

        // 禁用按钮防止复点击
        $(this).prop('disabled', true);
    });
}

function sendPlayCards(cardIds) {
    if (!currentRoom || !stompClient) return;

    const playCardMessage = {
        playerId: currentPlayer.id,
        playerName: currentPlayer.username,
        cardIds: cardIds,
        roomId: currentRoom.id
    };

    // 先从界面上移除这些牌
    cardIds.forEach(id => {
        $(`.card-item[data-card-id="${id}"]`).remove();
    });

    // 重新排列剩余的手牌
    const remainingCards = currentGameState.playerCards[currentPlayer.id]
        .filter(card => !cardIds.includes(card.id));
    displayCards(remainingCards, true);

    // 发送出牌消息
    stompClient.send(`/app/game/${currentRoom.id}/play`, {},
        JSON.stringify(playCardMessage));
}

function generateBidButtons(currentMaxBid) {
    const buttons = [];

    // 不叫永远可以选择
    buttons.push(`<button class="btn btn-outline-secondary bid-btn" data-bid="0">不叫</button>`);

    // 只能叫比当前最高分更高的分数
    if (currentMaxBid < 1) {
        buttons.unshift(`<button class="btn btn-outline-primary bid-btn" data-bid="1">1分</button>`);
    }
    if (currentMaxBid < 2) {
        buttons.unshift(`<button class="btn btn-outline-primary bid-btn" data-bid="2">2分</button>`);
    }
    if (currentMaxBid < 3) {
        buttons.unshift(`<button class="btn btn-outline-primary bid-btn" data-bid="3">3分</button>`);
    }

    return buttons.join('');
}

function updateGameUI(gameState) {
    console.log('Updating game UI with state:', gameState);
    currentGameState = gameState;

    // 清空游戏控制区域
    $('.game-controls').empty();

    // 根据游戏阶段显示不同的UI
    if (gameState.bidding) {
        showBiddingUI(gameState);
    } else if (gameState.playing) {
        showPlayingUI(gameState);
    }

    // 更新玩家牌
    if (gameState.playerCards && gameState.playerCards[currentPlayer.id]) {
        displayCards(gameState.playerCards[currentPlayer.id]);
    }

    // 更新其他玩家的手牌数量和角色
    const otherPlayers = gameState.room.players.filter(p => p.id !== currentPlayer.id);
    otherPlayers.forEach((player, index) => {
        const cardCount = gameState.playerCards[player.id] ? gameState.playerCards[player.id].length : 0;
        const playerSpot = index === 0 ? '#player1' : '#player2';
        const role = player.id === gameState.landlordId ? 'LANDLORD' : 'FARMER';

        // 更新玩家信息和手牌数量
        $(`${playerSpot} .player-info`).html(`
            <div class="player-name">${player.username}</div>
            <div class="card-count">剩余牌数: ${cardCount}</div>
            ${gameState.landlordRevealed ? `
                <div class="player-role ${role === 'LANDLORD' ? 'role-landlord' : 'role-farmer'}">
                    ${role === 'LANDLORD' ? '地主' : '农民'}
                </div>
            ` : ''}
        `);

        // 更新玩家手牌显示
        $(`${playerSpot} .player-cards`).html(generateCardBacks(cardCount));
    });

    // 更新当前玩家的角色显示
    if (gameState.landlordRevealed) {
        const currentPlayerRole = currentPlayer.id === gameState.landlordId ? 'LANDLORD' : 'FARMER';
        $('#currentPlayerRole').html(`
            <div class="player-role ${currentPlayerRole === 'LANDLORD' ? 'role-landlord' : 'role-farmer'}">
                ${currentPlayerRole === 'LANDLORD' ? '地主' : '农民'}
            </div>
        `);
    }

    // 更新当前玩家的角色显示
    if (gameState.landlordRevealed) {
        const isCurrentPlayerLandlord = currentPlayer.id === gameState.landlordId;
        const currentPlayerRole = isCurrentPlayerLandlord ? 'LANDLORD' : 'FARMER';
        $('#currentPlayerRole').html(`
            <div class="player-role ${currentPlayerRole === 'LANDLORD' ? 'role-landlord' : 'role-farmer'}">
                ${currentPlayerRole === 'LANDLORD' ? '地主' : '农民'}
            </div>
        `);
    }

    // 更新地主牌
    if (gameState.landlordRevealed && gameState.landlordCards) {
        displayLandlordCards(gameState.landlordCards);
    }

    // 更新游戏信息
    updateGameInfo(gameState);

    // 更新出牌区域
    if (gameState.lastPlayedCards && gameState.lastPlayedCards.length > 0) {
        displayPlayedCards(gameState.lastPlayedCards, gameState.lastPlayerId);
    }

    // 如果游戏结束，显示结算界面
    if (gameState.winner) {
        handleGameOver(gameState);
    }
}

function updateGameInfo(gameState) {
    // 更新倍数
    $('#currentMultiple').text(gameState.multiple || 1);

    // 更新玩家角色
    if (gameState.landlordId) {
        const isLandlord = gameState.landlordId === currentPlayer.id;
        $('.player-role').text(isLandlord ? '地主' : '农民');
        $('.player-role').removeClass('role-landlord role-farmer')
            .addClass(isLandlord ? 'role-landlord' : 'role-farmer');
    }

    // 更新游戏记录
    if (gameState.lastAction) {
        addGameHistory(gameState.lastAction);
    }
}

function displayLandlordCards(cards) {
    const landlordCardsContainer = $('.landlord-cards-container');
    landlordCardsContainer.empty();

    cards.forEach(card => {
        const cardElement = `
            <div class="landlord-card">
                <div class="card-inner">
                    <span class="card-suit ${isRedSuit(card.suit, card.rank) ? 'red' : ''}">${getSuitSymbol(card.suit)}</span>
                    <span class="card-rank ${isRedSuit(card.suit, card.rank) ? 'red' : ''}">${card.rank}</span>
                </div>
            </div>
        `;
        landlordCardsContainer.append(cardElement);
    });
}

function addGameHistory(action) {
    const historyItem = `
        <div class="history-item">
            <span class="player-name">${action.playerName}</span>
            <span class="action-text">${getActionText(action)}</span>
        </div>
    `;
    $('#playHistory').append(historyItem);

    // 滚动到底部
    const historyList = $('#playHistory');
    historyList.scrollTop(historyList[0].scrollHeight);
}

function getActionText(action) {
    switch(action.type) {
        case 'BID':
            return `叫分: ${action.points}`;
        case 'PLAY':
            return `出牌: ${formatCards(action.cards)}`;
        case 'PASS':
            return '不出';
        case 'READY':
            return '准备';
        case 'LEAVE':
            return '离开了游戏';
        case 'JOIN':
            return '加入了游戏';
        case 'GAME_START':
            return '游戏开始';
        default:
            return action.text || '';
    }
}

function formatCards(cards) {
    if (!cards || !Array.isArray(cards) || cards.length === 0) {
        return '';
    }

    return cards.map(card => {
        let suitSymbol = getSuitSymbol(card.suit);
        // 对于大小王做特殊处理
        if (card.suit === 'JOKER') {
            return card.rank === 'BIG' ? '大王' : '小王';
        }
        return `${card.rank}${suitSymbol}`;
    }).join(' ');
}

function getSuitSymbol(suit) {
    switch(suit) {
        case 'HEARTS': return '♥';
        case 'SPADES': return '♠';
        case 'CLUBS': return '♣';
        case 'DIAMONDS': return '♦';
        default: return suit;
    }
}

function getStatusText(status) {
    switch(status) {
        case 'WAITING': return '等待中';
        case 'PLAYING': return '游戏中';
        case 'FINISHED': return '已结束';
        case 'CLOSED': return '已关闭';
        default: return status;
    }
}

function handlePrivateMessage(message) {
    if (message.type === 'ERROR') {
        showGameMessage(message.content, 'error');
    }
}

function leaveRoom() {
    if (!currentRoom || !stompClient) return;

    try {
        // 发送离开房间消息
        stompClient.send(`/app/room/${currentRoom.id}/leave`, {},
            JSON.stringify(currentPlayer));

        // 断开 WebSocket 连接
        if (stompClient.connected) {
            stompClient.disconnect(() => {
                console.log('WebSocket disconnected');
                // 返回大厅
                window.location.href = '/';
            });
        } else {
            window.location.href = '/';
        }
    } catch (error) {
        console.error('Error leaving room:', error);
        // 即使发生错误也返回大厅
        window.location.href = '/';
    }
}

function updateReadyButton(room) {
    const currentPlayerInRoom = room.players.find(p => p.id === currentPlayer.id);
    const readyBtn = $('#readyBtn');

    if (currentPlayerInRoom) {
        if (currentPlayerInRoom.ready) {
            readyBtn.removeClass('btn-primary').addClass('btn-warning');
            readyBtn.html('<i class="fas fa-times"></i> 取消准备');
        } else {
            readyBtn.removeClass('btn-warning').addClass('btn-primary');
            readyBtn.html('<i class="fas fa-check"></i> 准备');
        }

        // 如果游戏已经开始，禁用准备按钮
        if (room.status === 'PLAYING') {
            readyBtn.prop('disabled', true);
            readyBtn.removeClass('btn-primary btn-warning').addClass('btn-secondary');
        } else {
            readyBtn.prop('disabled', false);
        }
    }
}

function showPlayingTips(cards) {
    const pattern = CardUtils.getPattern(cards);
    const description = CardUtils.getPatternDescription(pattern);

    if (pattern === CardPattern.INVALID) {
        showGameMessage('选择的牌不符合规则', 'warning');
    } else {
        showGameMessage(`当前牌型: ${description}`, 'info');
    }
}

function sendBid(points) {
    if (!currentRoom || !stompClient) return;

    stompClient.send(`/app/game/${currentRoom.id}/bid`, {},
        JSON.stringify({
            playerId: currentPlayer.id,
            bidPoints: points
        }));
}

function displayPlayedCards(cards, playerId) {
    const playedCardsArea = $('#lastPlayedCards');
    playedCardsArea.empty();

    if (!cards || cards.length === 0) return;

    const stackContainer = $('<div class="played-card-stack"></div>');
    playedCardsArea.append(stackContainer);

    // 获取起始位置（玩家手牌区域）
    const myCardsArea = $('#myCards');
    const myCardsRect = myCardsArea[0].getBoundingClientRect();
    const playedAreaRect = playedCardsArea[0].getBoundingClientRect();

    // 计算中心点位置
    const centerX = (playedAreaRect.width - 80) / 2; // 80是卡牌宽度
    const centerY = (playedAreaRect.height - 120) / 2; // 120是卡牌高度

    cards.forEach((card, index) => {
        const cardElement = $(`
            <div class="played-card" data-card-id="${card.id}">
                <div class="card-inner">
                    <span class="card-suit ${isRedSuit(card.suit, card.rank) ? 'red' : ''}">${getSuitSymbol(card.suit)}</span>
                    <span class="card-rank ${isRedSuit(card.suit, card.rank) ? 'red' : ''}">${card.rank}</span>
                </div>
            </div>
        `);

        stackContainer.append(cardElement);

        // 设置动画起始位置
        let startX, startY;
        if (playerId === currentPlayer.id) {
            // 如果是前玩家出的牌，从手牌区域开始
            startX = myCardsRect.left - playedAreaRect.left + (index * 30);
            startY = myCardsRect.top - playedAreaRect.top;
        } else {
            // 如果是其他玩家出的牌，从对应玩家位置开始
            const playerPosition = getPlayerPosition(playerId);
            startX = playerPosition.x - playedAreaRect.left;
            startY = playerPosition.y - playedAreaRect.top;
        }

        // 计算每张牌的目标位置（稍微错开）
        const endX = centerX + (index - (cards.length - 1) / 2) * 30;
        const endY = centerY;

        // 添加随机旋转角度
        const randomRotate = Math.random() * 20 - 10;

        // 设置CSS变量
        cardElement.css({
            '--start-x': `${startX}px`,
            '--start-y': `${startY}px`,
            '--end-x': `${endX}px`,
            '--end-y': `${endY}px`,
            '--random-rotate': `${randomRotate}deg`
        });

        // 添加动画
        cardElement.css('animation', 'playCardAnimation 0.5s forwards');

        // 动画结束后设置最终位置
        setTimeout(() => {
            cardElement.css({
                'transform': `translate(${endX}px, ${endY}px)`,
                'z-index': index
            });
        }, 500);
    });
}

// 获取玩家位置
function getPlayerPosition(playerId) {
    const players = currentRoom.players;
    const playerIndex = players.findIndex(p => p.id === playerId);
    const playersCount = players.length;

    // 获取玩家区域的位置
    const player1Area = $('#player1')[0].getBoundingClientRect();
    const player2Area = $('#player2')[0].getBoundingClientRect();

    switch(playerIndex) {
        case 0: // 左边玩家
            return {
                x: player1Area.right,
                y: player1Area.top + player1Area.height / 2
            };
        case 1: // 右边玩家
            return {
                x: player2Area.left,
                y: player2Area.top + player2Area.height / 2
            };
        default:
            return {x: 0, y: 0};
    }
}

// 页面加载完成后初始化游戏
$(document).ready(function() {
    AudioManager.init();
    initGame();
});

// 修改页面关闭事件处理
window.onbeforeunload = function(e) {
    if (currentRoom && stompClient && stompClient.connected) {
        // 页面关闭时不发送离开消息，让服务端通过断开连接事件处理
        stompClient.disconnect();
    }
};

// 添加重连逻辑
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

function handleConnectionError() {
    if (reconnectAttempts < maxReconnectAttempts) {
        reconnectAttempts++;
        const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 10000);
        showGameMessage(`连接断开，${delay/1000}秒后尝试重新连接...`, 'warning');

        setTimeout(function() {
            connect(currentRoom.id);
        }, delay);
    } else {
        showGameMessage('连接失败，请刷新页面重试', 'error');
        // 可以选择自动返回大厅
        // setTimeout(() => window.location.href = '/', 3000);
    }
}

// 添加自动重连检查
setInterval(function() {
    if (currentRoom && (!stompClient || !stompClient.connected) && reconnectAttempts < maxReconnectAttempts) {
        console.log('Checking connection status...');
        connect(currentRoom.id);
    }
}, 5000);

// 使用 MessageUI 来显示游戏消息
function showGameMessage(message, type = 'info') {
    MessageUI.showMessage(message, type);
}

// 使用 ErrorHandler 来处理错误
function handleError(error, defaultMessage = '操作失败') {
    ErrorHandler.handleError(error, defaultMessage);
}

// 使用 AudioManager 来播放音效
function playCardSound(type) {
    AudioManager.playSound(type);
}

// 添加移动端菜单初始化函数
function initMobileMenu() {
    $('.menu-toggle').click(function() {
        $('.mobile-menu').addClass('active');
    });

    $('.close-menu').click(function() {
        $('.mobile-menu').removeClass('active');
    });

    // 点击菜单外区域关闭菜单
    $(document).click(function(event) {
        if (!$(event.target).closest('.mobile-menu, .menu-toggle').length) {
            $('.mobile-menu').removeClass('active');
        }
    });
}

// 将 updateMobilePlayersList 函数添加到全局作用域
function updateMobilePlayersList(players) {
    const mobilePlayersList = $('#mobilePlayersList');
    mobilePlayersList.empty();

    players.forEach(player => {
        const isCurrentPlayer = player.id === currentPlayer.id;
        const playerItem = `
            <li class="mobile-player-item">
                <div class="player-info">
                    <span class="player-name">
                        ${player.username}
                        ${isCurrentPlayer ? '(我)' : ''}
                    </span>
                    <span class="player-status">
                        ${player.ready ?
            '<span class="player-ready">已准备</span>' :
            '<span class="player-waiting">未准备</span>'
        }
                    </span>
                </div>
                ${player.cards ? `
                    <div class="card-count">
                        剩余牌数: ${player.cards.length}
                    </div>
                ` : ''}
                ${player.role ? `
                    <div class="player-role ${player.role === 'LANDLORD' ? 'role-landlord' : 'role-farmer'}">
                        ${player.role === 'LANDLORD' ? '地主' : '农民'}
                    </div>
                ` : ''}
            </li>
        `;
        mobilePlayersList.append(playerItem);
    });

    // 更新移动端游戏统计信息
    if (currentGameState) {
        $('.mobile-menu .game-stats').html(`
            <div class="stat-item">
                <span class="stat-label">当前倍数:</span>
                <span class="stat-value">${currentGameState.multiple || 1}</span>
            </div>
            ${currentGameState.bombCount ? `
                <div class="stat-item">
                    <span class="stat-label">炸弹数:</span>
                    <span class="stat-value">${currentGameState.bombCount}</span>
                </div>
            ` : ''}
        `);
    }
}

function handleGameOver(gameState) {
    const modal = $('#gameOverModal');
    const scoreList = $('#scoreList');
    scoreList.empty();

    // 获取玩家得分信息
    const scores = gameState.playerScores;
    const players = gameState.room.players;

    // 生成得分列表
    players.forEach(player => {
        const score = scores[player.id];
        const role = player.role === 'LANDLORD' ? '地主' : '农民';
        const scoreClass = score >= 0 ? 'positive' : 'negative';
        const isWinner = player.id === gameState.winner;

        const scoreItem = `
            <div class="score-item">
                <div class="player-info">
                    <span class="player-name">${player.username}</span>
                    <span class="player-role ${player.role.toLowerCase()}">${role}</span>
                    ${isWinner ? '<span class="winner-badge"><i class="fas fa-crown"></i></span>' : ''}
                </div>
                <div class="score-value ${scoreClass}">
                    ${score >= 0 ? '+' : ''}${score}
                </div>
            </div>
        `;
        scoreList.append(scoreItem);
    });

    // 显示弹窗
    modal.modal({
        backdrop: 'static',
        keyboard: false
    });

    // 倒计时
    let countdown = 5;
    const countdownElement = $('#countdown');
    const countdownInterval = setInterval(() => {
        countdown--;
        countdownElement.text(countdown);

        if (countdown <= 0) {
            clearInterval(countdownInterval);
            modal.modal('hide');
            // 重置游戏状态
            resetGameState();
        }
    }, 1000);
}

function resetGameState() {
    // 重置游戏界面
    $('#lastPlayedCards').empty();
    $('#myCards').empty();
    $('.player-spot').each(function() {
        $(this).find('.card-count').text('17');
        $(this).find('.player-role').text('');
    });

    // 重置按钮状态
    $('#playCards').prop('disabled', true);
    $('#pass').prop('disabled', true);

    // 清除地主牌显示
    $('.landlord-cards-container').empty();

    // 重置游戏信息
    $('#currentMultiple').text('1');
    $('.player-role').text('');

    // 显示等待提示
    showGameMessage('等待新一局游戏开始...', 'info');
}



